package music

import (
	"context"
	"fmt"
	"time"

	"go-weixin/app/music/musicapi/internal/svc"
	"go-weixin/app/music/musicapi/internal/types"
	"go-weixin/app/music/musicrpc/pb/proto/music"

	"go-weixin/common/apiserver"
	"go-weixin/common/ctxdata"

	"github.com/zeromicro/go-zero/core/logx"
)

type MusicQueryArtistLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMusicQueryArtistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MusicQueryArtistLogic {
	return &MusicQueryArtistLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MusicQueryArtistLogic) MusicQueryArtist(req *types.MusicQueryArtistReq) (resp *types.MusicQueryArtistResp, err error) {
	if uid := ctxdata.GetUidFromCtx(l.ctx); uid != 0 {
		f_r_key := fmt.Sprintf("req_flow_restriction_%d", uid)
		if uid != 0 {
			err := apiserver.ReqFlowRestriction(l.svcCtx.ChenCache, int(uid), f_r_key, 3)
			if err != nil {
				return nil, err
			}
		}
	}
	// cacheCtx, cacheCanelFunc := context.WithTimeout(context.Background(), 1*time.Second)
	// defer cacheCanelFunc()
	// uid := ctxdata.GetUidFromCtx(l.ctx)
	// f_r_key := fmt.Sprintf("req_flow_restriction_%d", uid)
	// if has, err := l.svcCtx.ChenCache.SetnxCtx(cacheCtx, f_r_key, "req"); err != nil {
	// 	return nil, errors.New(7000, "redis-setnx:"+err.Error())
	// } else {
	// 	if has {
	// 		// 设置key成功时(添加超时时间,允许请求)
	// 		err = l.svcCtx.ChenCache.ExpireCtx(cacheCtx, f_r_key, 3)
	// 		if err != nil {
	// 			return nil, errors.New(7000, "redis-expire:"+err.Error())
	// 		}
	// 	} else {
	// 		// 设置key失败时(检查超时时间,终止请求)
	// 		t, err := l.svcCtx.ChenCache.TtlCtx(cacheCtx, f_r_key)
	// 		if err != nil {
	// 			return nil, errors.New(7000, "redis-ttl:"+err.Error())
	// 		}
	// 		if t == -2 {
	// 			// 不存在key
	// 			return nil, errors.New(7000, "redis-ttl: 不存在key")
	// 		}
	// 		if t == -1 {
	// 			// key没有超时时间
	// 			err = l.svcCtx.ChenCache.ExpireCtx(cacheCtx, f_r_key, 3)
	// 			if err != nil {
	// 				return nil, err
	// 			}
	// 		}
	// 		return nil, errors.New(7000, "请求频繁")
	// 	}
	// }

	ctx, canelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer canelFunc()
	rpcResp, err := l.svcCtx.MusicRpc.MusicQueryArtist(ctx, &music.MusicQueryArtistReq{
		Artist: req.Artist,
		Page:   req.Page,
	})
	if err != nil {
		return nil, err
	}
	var musciList []types.Music
	if len(rpcResp.MusicList) > 0 {
		for _, m := range rpcResp.MusicList {
			musciList = append(musciList, types.Music{
				Id:      m.Id,
				Title:   m.Title,
				Artist:  m.Artist,
				Path:    m.Path,
				Md5:     m.Md5,
				Year:    m.Year,
				Size:    m.Size,
				Pictrue: m.Pictrue,
			})
		}
	}
	resp = new(types.MusicQueryArtistResp)
	resp.MusicList = musciList
	return
}
